using System.Collections.Generic;
using NodeCanvas.Variables;
using UnityEngine;

namespace NodeCanvas
{
	[AddComponentMenu("NodeCanvas/Sync Mecanim")]
	public class SyncMecanim : MonoBehaviour
	{
		public Blackboard blackboard;

		public Animator animator;

		public List<string> parameters = new List<string>();

		private List<VariableData> syncedVariables = new List<VariableData>();

		private void Reset()
		{
			blackboard = GetComponent<Blackboard>();
			animator = GetComponent<Animator>();
		}

		private void Awake()
		{
			if (!blackboard || !animator)
			{
				return;
			}
			foreach (string parameter in parameters)
			{
				VariableData data = blackboard.GetData(parameter, null);
				if (data == null)
				{
					Debug.LogWarning(string.Format("MecanimSync: Blackboard does not have variable with name '{0}'", parameter));
				}
				else if (!syncedVariables.Contains(data))
				{
					syncedVariables.Add(data);
					data.onValueChanged += OnValueChanged;
				}
			}
		}

		private void OnDestroy()
		{
			foreach (VariableData syncedVariable in syncedVariables)
			{
				syncedVariable.onValueChanged -= OnValueChanged;
			}
		}

		private void OnValueChanged(string name, object value)
		{
			if (value.GetType() == typeof(bool))
			{
				animator.SetBool(name, (bool)value);
			}
			else if (value.GetType() == typeof(float))
			{
				animator.SetFloat(name, (float)value);
			}
			else if (value.GetType() == typeof(int))
			{
				animator.SetInteger(name, (int)value);
			}
		}
	}
}
